"use client";

import React, { useRef } from 'react';
import {
  PageContainer,
  ProTable,
  ProColumns,
} from "@ant-design/pro-components";
import { Button, Tag, App } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DollarOutlined,
  CreditCardOutlined,
  ContainerOutlined,
} from "@ant-design/icons";
import { useRouter } from 'next/navigation';
import type { ActionType, RequestData } from "@ant-design/pro-components";
import { TeamInfo, TeamStatus, TeamPageQueryParams } from "@/types/team";
import { teamApi } from "@/apis/team";
import TeamBalanceRechargeModal from "./components/TeamBalanceRechargeModal";
import { useOverlayManager } from "@/hooks/useOverlayManager";
import TeamCreditModal from "./components/TeamCreditModal";

interface TableParams {
  pageSize?: number;
  current?: number;
  keyword?: string;
}

interface TableSort {
  [key: string]: "ascend" | "descend" | null;
}

interface TableFilter {
  [key: string]: (string | number)[] | null;
}

const TeamsPage: React.FC = () => {
  const router = useRouter();
  const actionRef = useRef<ActionType>(null);
  const { openOverlay } = useOverlayManager();
  const { message: appMessage } = App.useApp();

  const columns: ProColumns<TeamInfo>[] = [
    {
      title: "ID",
      dataIndex: "id",
      width: 80,
      search: false,
    },
    {
      title: "团队名称",
      dataIndex: "name",
      width: 200,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      valueType: "select",
      valueEnum: {
        [TeamStatus.NORMAL]: { text: '正常' },
        [TeamStatus.DISABLED]: { text: '禁用' },
      },
      render: (_, record) => (
        <Tag color={record.status === TeamStatus.NORMAL ? "green" : "red"}>
          {record.status === TeamStatus.NORMAL ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: "团队折扣",
      dataIndex: "discount",
      width: 100,
      search: false,
      render: (_, record) => `${record.discount}折`,
    },
    {
      title: "备注",
      dataIndex: "notes",
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      width: 180,
      search: false,
      valueType: "dateTime",
    },
    {
      title: "操作",
      valueType: "option",
      width: 300,
      render: (_, record) => [
        <Button
          key={`edit-${record.id}`}
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => {
            router.push(`/teams/${record.id}`);
          }}
        >
          编辑
        </Button>,
        <Button
          key={`bill-${record.id}`}
          type="link"
          size="small"
          icon={<ContainerOutlined />}
          onClick={() => {
            router.push(`/teams/${record.id}/bill`);
          }}
        >
          账单
        </Button>,
        <Button
          key={`recharge-${record.id}`}
          type="link"
          size="small"
          icon={<DollarOutlined />}
          onClick={() => {
            openOverlay({
              name: "team-balance-recharge-modal",
              Overlay: TeamBalanceRechargeModal,
              props: {
                teamId: record.id.toString(),
                teamName: record.name,
                onSuccess: () => {
                  actionRef.current?.reload();
                },
              },
              openProp: "open",
            });
          }}
        >
          余额充值
        </Button>,
        <Button
          key={`credit-${record.id}`}
          type="link"
          size="small"
          icon={<CreditCardOutlined />}
          onClick={() => {
            openOverlay({
              name: "team-credit-modal",
              Overlay: TeamCreditModal,
              props: {
                teamId: record.id.toString(),
                teamName: record.name,
                onSuccess: () => {
                  actionRef.current?.reload();
                },
              },
              openProp: "open",
            });
          }}
        >
          额度设置
        </Button>,
      ],
    },
  ];

  const fetchTeams = async (
    params: TableParams,
  ): Promise<Partial<RequestData<TeamInfo>>> => {
    try {
      const queryParams: TeamPageQueryParams = {
        current: params.current,
        size: params.pageSize,
        searchKey: params.keyword,
      };

      const response = await teamApi.getTeamPageList(queryParams);
      
      return {
        data: response.records,
        success: true,
        total: response.total,
      };
    } catch (error) {
      console.error("获取团队列表失败:", error);
      appMessage.error("获取团队列表失败");
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  return (
    <App>
      <PageContainer title="团队管理" content="管理团队信息、余额、额度和成员">
        <ProTable<TeamInfo>
          headerTitle="团队列表"
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: "auto",
          }}
          toolBarRender={() => [
            <Button
              key="add"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                router.push('/teams/new');
              }}
              style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
            >
              新建团队
            </Button>,
          ]}
          request={fetchTeams}
          columns={columns}
          pagination={{
            defaultPageSize: 20,
            showSizeChanger: true,
          }}
        />
      </PageContainer>
    </App>
  );
};

export default TeamsPage;
